package dao;

import static org.junit.Assert.fail;

import generators.IslandGenerator;

import java.util.ArrayList;
import java.util.List;

import model.dao.IslandDAO;
import model.entity.Island;

import org.junit.Before;
import org.junit.Test;

import postgis.PointWrap;
import postgis.util.PostGISUtil;

import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.util.Assert;

public class IslandDAOtest {

	private IslandDAO dao;
	private IslandGenerator generator;

	@Before
	public void doBefore() {
		dao = new IslandDAO(Island.class);
		generator = new IslandGenerator();
	}

	@Test
	public void testFindAllNearIn() {
		// Ponto dentro
		Point p = null;
		try {
			p = PostGISUtil.getPoint(-38.54955419898033, -3.7234314574558613);
		} catch (ParseException e) {
			fail("ParseException");
		}
		Island iGenerated = generator.generate(1).get(0);
		List<Island> is = dao.findAllNear(p, 1.);
		boolean isIn = false;
		for(Island i : is) {
			if(i.getId().equals(iGenerated.getId())) {
				isIn = true;
				break;
			}
		}
		Assert.isTrue(isIn, "Ponto não está dentro da ilha");
	}

	@Test
	public void testFindAllNearOut() {
		// Ponto dentro
		Point p = null;
		try {
			p = PostGISUtil.getPoint(-38.549205511808395,-3.7234100450775385);
		} catch (ParseException e) {
			fail("ParseException");
		}
		List<Island> is = dao.findAllNear(p, PostGISUtil.getDistanceInAngle(20));
//		System.out.println(p.distance(is.get(0).getShape())*(Math.PI/180) * 6378137+"m");
		Assert.isTrue(is.size() == 0, "Ponto não está a distancia da ilha");
	}
	@Test
	public void testGISInDatabase() {
		List<PointWrap> points = new ArrayList<PointWrap>();
		PointWrap point = new PointWrap(-38.54955554008484, -3.7233043214519403);
		points.add(point);
		point = new PointWrap(-38.54963734745979, -3.723558593441424);
		points.add(point);
		point = new PointWrap(-38.54954481124878, -3.723585358909731);
		points.add(point);
		point = new PointWrap(-38.54946970939636, -3.7233284103804074);
		points.add(point);
		point = new PointWrap(-38.54955554008484, -3.7233043214519403);
		points.add(point);
		IslandGenerator generator = new IslandGenerator();
		generator.generate(1).get(0);
		Island i = dao.findAll().get(0);
		Polygon p = null;
		try {
			p = PostGISUtil.getPolygon(points, null);
		} catch (ParseException e) {
			fail("ParseException");
		}
		Assert.equals(i.getShape().toText(), p.toText());
	}

}
